//
//  HSTool.m
//  mobile
//
//  Created by li on 2017/9/8.
//  Copyright © 2017年 li. All rights reserved.
//

#import "HSTool.h"
#import <WebKit/WebKit.h>
#import "AppDelegate.h"

@implementation HSTool


+ (void)deleteFileWithFilePath:(NSString *)filePath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL blHave = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!blHave) {
        HSLog(@"%@ 文件不存在", filePath);
        return ;
    }else {
        BOOL blDele= [fileManager removeItemAtPath:filePath error:nil];
        if (blDele) {
            HSLog(@"%@ 删除成功", filePath);
        }else {
            HSLog(@"%@ 删除失败", filePath);
        }
    }
}

+ (UIImage *)createImageWithColor:(UIColor *)color andHeight:(CGFloat)height{
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, height);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return theImage;
}

+ (UIWindow *)getWindow{
    UIApplication *app = [UIApplication sharedApplication];
    return app.delegate.window;
}

+ (UIViewController *)getCurrentViewController{
    UIViewController *vc = [UIApplication sharedApplication].delegate.window.rootViewController;
    while (YES) {
        if ([vc isKindOfClass:UINavigationController.class]) {
            UINavigationController *nav = (UINavigationController *)vc;
            vc = nav.viewControllers.lastObject;
        }else if ([vc isKindOfClass:UITabBarController.class]) {
            UITabBarController *tab = (UITabBarController *)vc;
            vc = tab.viewControllers[tab.selectedIndex];
        }else if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    
    return vc;
}

#pragma mark --(收键盘)
+ (UIView *)getInputAccessoryViewForCloseKeyboard
{
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 44)];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *close = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(closeKB:)];
    close.tintColor = kMainColor;
    toolBar.items = @[space, close];
    return toolBar;
}

+(void)closeKB:(id)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

//设置状态栏颜色
+ (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    if(@available(iOS 13.0, *)){
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        UIView *statusBar = keyWindow.subviews.lastObject;
        if(statusBar.tag != 999999){
            statusBar = [[UIView alloc] initWithFrame:keyWindow.windowScene.statusBarManager.statusBarFrame];
            statusBar.tag = 999999;
        }
        statusBar.backgroundColor = color;
        [keyWindow addSubview:statusBar];
    }else{
        UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
        if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
            statusBar.backgroundColor = color;
        }
    }
}

+ (void)clearWebCache {
    // 清理网页缓存
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *websiteDataTypes = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
                                                        WKWebsiteDataTypeOfflineWebApplicationCache,
                                                        WKWebsiteDataTypeMemoryCache,
                                                        WKWebsiteDataTypeLocalStorage,
                                                        WKWebsiteDataTypeCookies,
                                                        WKWebsiteDataTypeSessionStorage,
                                                        WKWebsiteDataTypeIndexedDBDatabases,
                                                        WKWebsiteDataTypeWebSQLDatabases
                                                        ]];
        
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{}];
        
    }else {
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
}

+ (void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor{
    
    if (!(labell && font && vaColor)) {
        return;
    }
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text];
    //设置字号
    [str addAttribute:NSFontAttributeName value:font range:range];
    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    labell.attributedText = str;
}

#pragma mark NSString NSDictionary NSData

///NSDictionary 转 NSString
- (NSString *)getStringWithDictionary:(NSDictionary *)dictionary{
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
    NSString *resultString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return resultString;
}

///NSString非空判断

+ (BOOL)stringIsEmpty:(NSString *)string{
    
    BOOL result = NO;
    
    if ( nil == string
        || [string isKindOfClass:[NSNull class]]
        || [string isEqualToString:@""]){
        result = YES;
    }
    
    return result;
}

///NSString过滤特殊指定字符
+ (NSString *)filterString:(NSString *)string rule:(NSString *)rule{
    
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:rule];
    
    // 过滤字符串的特殊字符
    return  [string stringByTrimmingCharactersInSet:set];
}

// 判断手机号码地址格式
+ (BOOL)isMobileNumber:(NSString *)mobileNum{
    
    if (mobileNum.length < 7) {
        return NO;
    }
    
    //  mobileNum = [mobileNum substringFromIndex:6];
    NSString *tel = @"^(\\d{3,4}-)\\d{7,8}$";
    NSString *mob = @"^1\\d{10}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", tel];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mob];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)){
        return YES;
    }else{
        return NO;
    }
}

///图片base64编码
+ (NSString *)getBase64Image:(UIImage *)originImage{
    NSData *data = UIImageJPEGRepresentation(originImage, 0.7f);
    HSLog(@"y图片大小：%ld",data.length / 1024.0);
    
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}



///NSString Base64
+ (NSString *)getBase64:(NSString *)input{
    NSData *inputData = [input dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64string = [inputData base64EncodedStringWithOptions:0];
    
    return base64string;
}

///解码 Base64
+ (NSString *)getStringFromBase64:(NSString *)input{
    
    NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:input options:0];
    NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
    return decodedString;
}

///NSString转NSData
+ (NSData *)getDataFromString:(NSString *)input{
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}

///NSData转NSString
+ (NSString *)getStringFromData:(NSData *)input{
    NSString *string = [[NSString alloc] initWithData:input encoding:NSUTF8StringEncoding];
    return string;
}

///NSDictionary转NSString
+ (NSString *)getStringFromDictionary:(NSDictionary *)input{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:input
                                                       options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

///NSString转NSDictionary或数组
+ (id)getDictionaryFromString:(NSString *)input{
    if (kStringIsEmpty(input)) {
        return nil;
    }
    
    NSData * data = [input dataUsingEncoding:NSUTF8StringEncoding];
    id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return obj;
}

///NSData转NSDictionary
+ (NSDictionary *)getDictionaryFromData:(NSData *)input{
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:input options:NSJSONReadingMutableLeaves error:nil];
    return jsonDict;
}

///NSDictionary转NSData
+ (NSData *)getDataFromDictionary:(NSDictionary *)input{
    NSData *data =   [NSJSONSerialization dataWithJSONObject:input options:NSJSONWritingPrettyPrinted error:nil];
    return data;
}

///获取文字显示所需的高度
+ (CGFloat)textHeightWithWidth:(CGFloat)width font:(UIFont *)font text:(NSString *)text
{
    CGSize constraint = CGSizeMake(width, MAXFLOAT);
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
    CGSize size = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading  attributes:dic context:nil].size;
    return ceil(size.height);       // ceil 取整函数
}

//普通字符串转换为十六进制的
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha{
    
    hexString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    UIColor *defaultColor = [UIColor clearColor];
    
    if (hexString.length < 6)
        return defaultColor;
    if ([hexString hasPrefix:@"#"]) hexString = [hexString substringFromIndex:1];
    if ([hexString hasPrefix:@"0X"]) hexString = [hexString substringFromIndex:2];
    if (hexString.length != 6) return defaultColor;
    
    //method1
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    unsigned int hexNumber;
    if (![scanner scanHexInt:&hexNumber]) return defaultColor;
    
    //method2
    const char *char_str = [hexString cStringUsingEncoding:NSASCIIStringEncoding];
    int hexNum;
    sscanf(char_str, "%x", &hexNum);
    return kHexColorA(hexNum, alpha);
}

+ (CGFloat)statusbarHeight {
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    return rectStatus.size.height; 
}

+ (CGFloat)navBarHeight{
     UITabBarController *tabCon = (UITabBarController *)[UIApplication sharedApplication].delegate.window.rootViewController;
    UINavigationController *con = (UINavigationController *)[tabCon.viewControllers firstObject];
    return con.navigationBar.height + [self statusbarHeight];
}
+ (CGFloat)tabBarHeight{
    UITabBarController *tabCon = (UITabBarController *)[UIApplication sharedApplication].delegate.window.rootViewController;
    CGRect rectTabBar = tabCon.tabBar.frame;
    return rectTabBar.size.height;
}

+ (BOOL)isEmail:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
}

///时间戳转NSString(毫秒 )
+ (NSString *)getTimeWithTimeInterval:(NSString *)timeInterval isLong:(BOOL)isLong{
    
    long interval = [timeInterval longLongValue] / (isLong ? 1000 : 1);
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    return dateString;
}

@end
